package su.jet.irc.client.service;

import java.io.IOException;
import java.util.List;

import su.jet.common.irc.domain.*;
import su.jet.common.irc.protocol.Session;
import su.jet.common.irc.protocol.request.LogoutRequest;

public class ReceiveService implements Runnable {
	private Session connectionWithServer;
	private Session connectionWithReader;
	private Message message;
	private User user;
	private MessageHandler messageHandler; //[ek] TODO try DI here
	private Thread thread;
	private Object o;

	public ReceiveService(Session connectionWithServer,
			Session connectionWithReader,
			MessageHandler messageHandler) {
		this.connectionWithServer = connectionWithServer;
		this.connectionWithReader = connectionWithReader;
		this.messageHandler = messageHandler;
		thread = new Thread(this);
	}
	
	public void start() {
		thread.start();
	}

	@SuppressWarnings("unchecked")
	@Override
	public void run() {
		user = messageHandler.getSender();
        try {
			while (true) {
				o = connectionWithServer.recieveObject();
				if (o instanceof List) {
					StringBuffer historyText = new StringBuffer();
					historyText.append("\n");
					for(String line: (List<String>)o)
						historyText.append(line + "\n");
						messageHandler.sendTextToReaderApplication(historyText.toString(), connectionWithReader);
				} else {
					message = (Message)o;
					messageHandler.sendTextToReaderApplication(message, connectionWithReader);
					
					if (message.getReceiver() != null)
						if (message.getSender().equals(user))
							if (!message.getReceiver().getNickName().equals(message.getSender().getNickName()))
								if (!message.getIsDelivered())
									connectionWithReader.sendObject("Message is not delivered");
				
					if (message.getText().equals("end") && message.getSender().equals(user)) {
						connectionWithServer.sendRequest(new LogoutRequest(user));
						connectionWithServer.disconnect();
						break;
					}
				}
			}
		} catch (ClassNotFoundException e) { 
			messageHandler.sendTextToReaderApplication("!!! Data processing error", connectionWithReader);
		} catch (IOException e) {
			messageHandler.sendTextToReaderApplication("!!! Error. Server failed...", connectionWithReader);
		}
    }
}
